package shopping;

import shopping.mode.*;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 提供校验服务
 */
public class ServiceRpc {

    /**
     * 库存
     * 初始化库存100
     */
    private volatile static AtomicInteger atomicInteger = new AtomicInteger(100);
    /**
     * 用户集合
     */
    private volatile static Map<String,User> userMap = new ConcurrentHashMap<>();
    /**
     * 用户优惠券
     * key: 代表用户id
     */
    private volatile static Map<String, List<DiscountCoupon>> userDiscountCouponMap = new ConcurrentHashMap();

    /**
     * 订单
     * key:代表用户id
     */
    private volatile static Map<String,List<Order>> userOrderMap = new ConcurrentHashMap<>();

    /**
     * 地址
     * key：代表用户id
     */
    private volatile static Map<String,List<Address>> userAddressMap = new ConcurrentHashMap<>();

    /**
     * 门店
     * key：代表门店id
     */
    private volatile static Map<String,Store> storeMap = new ConcurrentHashMap<>();

    /**
     * 产品集合
     * key：代表门店id
     */
    private volatile static Map<String,List<Produce>> storeProduceMap = new ConcurrentHashMap<>();

    /**
     * 获取当前登录用户
     * @param loginName 用户登录名
     * @return 返回指定用户
     */
    public static User getCurrentLoginUser(String loginName) {
        return userMap.get(loginName);
    }

    /**
     * 初始化基础数据
     */
    static {
        initUser(); // 初始化用户
        initDiscountCoupons(); // 初始化优惠券
        initAddress(); // 初始化地址
        initProduces(); // 初始化产品
        initStores(); // 初始化门店
    }

    /**
     * 初始化门店
     */
    private static void initStores() {
        Store s1 = new Store("S001","可乐门店","科技经营","120.12","30.23","A123456");
        Store s2 = new Store("S002","龙祥门店","科技经营","120.12","30.23","A123456");
        Store s3 = new Store("S003","佳乐家门店","科技经营","120.12","30.23","A123456");
        Store s4 = new Store("S004","家佳源门店","科技经营","120.12","30.23","A123456");
        storeMap.put("S001",s1);
        storeMap.put("S002",s2);
        storeMap.put("S003",s3);
        storeMap.put("S004",s4);
    }

    /**
     * 初始化产品
     */
    private static void initProduces() {
        Produce p1 = new Produce("P001","经典1903",100.00,1,"S001",false,"2021/01/01 00:00:00","2021/12/31 23:59:59");
        Produce p2 = new Produce("P002","纯生",100.00,1,"S001",false,"2020/01/01 00:00:00","2021/12/31 23:59:59");
        Produce p3 = new Produce("P003","青岛啤酒",100.00,1,"S001",false,"2021/01/01 00:00:00","2021/12/31 23:59:59");
        Produce p4 = new Produce("P004","黑啤",100.00,1,"S001",true,"2021/01/01 00:00:00","2021/12/31 23:59:59");
        Produce p5 = new Produce("P005","白啤",100.00,1,"S001",true,"2021/01/01 00:00:00","2021/12/31 23:59:59");
        Produce p6 = new Produce("P006","银麦",100.00,1,"S001",true,"2021/01/01 00:00:00","2021/12/31 23:59:59");
        storeProduceMap.put("S001",Arrays.asList(p1,p2,p3,p4,p5,p6));
    }

    /**
     * 初始化地址
     */
    private static void initAddress() {
        Address a1 = new Address("A0001","zhangsan","青岛","山东","市南区",true);
        Address a2 = new Address("A0002","zhangsan","青岛","山东","市南区",true);
        Address a3 = new Address("A0003","zhangsan","青岛","山东","市南区",true);
        Address a4 = new Address("A0004","zhangsan","青岛","山东","市南区",true);
        Address a5 = new Address("A0005","zhangsan","青岛","山东","市南区",true);
        userAddressMap.put("zhangsan",Arrays.asList(a1,a2,a3,a4,a5));
    }

    /**
     * 初始化优惠券
     */
    private static void initDiscountCoupons() {
        /**
         * 七夕活动
         */
        DiscountCoupon a1 = new DiscountCoupon("D00001","zhangsan","七夕活动",100.00,true,"2021/04/10 00:00:00","2021/10/01 23:59:59","S001","QX","七夕特惠");
        DiscountCoupon a2 = new DiscountCoupon("D00002","zhangsan","七夕活动",200.00,false,"2021/04/10 00:00:00","2021/08/01 23:59:59","S001","QX","七夕特惠");
        DiscountCoupon a3 = new DiscountCoupon("D00003","zhangsan","七夕活动",300.00,false,"2021/07/01 00:00:00","2021/09/01 23:59:59","S001","QX","七夕特惠");
        DiscountCoupon a4 = new DiscountCoupon("D00004","zhangsan","七夕活动",100.00,true,"2021/04/10 00:00:00","2021/11/01 23:59:59","S001","QX","七夕特惠");
        DiscountCoupon a5 = new DiscountCoupon("D00005","zhangsan","七夕活动",100.00,true,"2021/05/10 00:00:00","2021/12/01 23:59:59","S001","QX","七夕特惠");
        userDiscountCouponMap.put("zhangsan",Arrays.asList(a1,a2,a3,a4,a5));
    }

    /**
     * 初始化用户
     */
    private static void initUser() {
        User zhangsan = new User("zhangsan","张三","10","","");
        User lisi = new User("lisi","李四","10","","");
        User wangwu = new User("wangwu","王五","10","","");
        User zhaoliu = new User("zhaoliu","赵六","10","","");
        User sunqi = new User("sunqi","孙七","10","","");
        createUsers(zhangsan,lisi,wangwu,zhaoliu,sunqi);
    }

    /**
     * 用户选择购物
     */
    public static TempOrder getTempOrder(String loginName) {

        User user = userMap.get(loginName);
        Address address = userAddressMap.get(user.getUserNo()).get(0);
        DiscountCoupon discountCoupon = userDiscountCouponMap.get(user.getUserNo()).get(0);

        Produce p1 = storeProduceMap.get("S001").get(0);
        Produce p2 = storeProduceMap.get("S001").get(1);
        Produce p3 = storeProduceMap.get("S001").get(2);

        TempOrder tempOrder = new TempOrder();
        tempOrder.setUser(user);
        tempOrder.setAddress(address);
        tempOrder.setProduces(Arrays.asList(p1,p2,p3));
        tempOrder.setDiscountCoupon(discountCoupon);
        return tempOrder;
    }


    /**
     * 添加用户集合
     * @param user
     */
    public static void createUsers(User... user) {
        Arrays.stream(user).forEach(u->{
            createUser(u);
        });
    }


    /**
     * 新建用户
     * @param user  新建用户
     * @return
     */
    public static User createUser(User user) {
        userMap.put(user.getUserNo(),user);
        return user;
    }

    /**
     * 新建地址
     * @param address 新增地址
     * @return 返回新增的地址
     */
    public static Address createAddress(Address address) {
        if(userAddressMap.containsKey(address.getUserId())) {
            List<Address> list = userAddressMap.get(address.getUserId());
            list.add(address);
        } else {
            List<Address> newList = new ArrayList<>();
            newList.add(address);
            userAddressMap.put(address.getUserId(), newList);
        }
        return address;
    }

    /**
     * 获取地址
     * @param loginName 指定人
     * @return 返回指定人的地址集合
     */
    public static List<Address> getAddress(String loginName) {
        if(userAddressMap.containsKey(loginName)) {
            return userAddressMap.get(loginName);
        }
        return new ArrayList<>();
    }

    /**
     * 通过指定人获取优惠券
     * @param loginName
     * @return
     */
    public static List<DiscountCoupon> getDiscountCouponByLoginName(String loginName) {
        return userDiscountCouponMap.get(loginName);
    }

    /**
     * 下单
     */



    /**
     * 校验库存
     * @param produce
     * @return
     */
    public synchronized static  Map<String,Object> checkReperty(Produce produce) {
        Map<String,Object> result = new HashMap<>();
        int currentNum = atomicInteger.get();
        if(currentNum <= 0) {
            result.put("success",false);
            result.put("msg","当前仓库已无库存！");
            return result;
        }
        int num = produce.getNum();
        if(num <= 0) {
            result.put("success",false);
            result.put("msg","下单产品数量不足1件，无法完成下单！");
            return result;
        }
        if(num > currentNum) {
            result.put("success",false);
            result.put("msg","当前库存已不足！");
            return result;
        }
        result.put("success",true);
        result.put("msg","校验成功！");
        return result;
    }


    public static Map<String,Object> checkAddressByUser(User user,Address address) {
        Map<String,Object> result = new HashMap<>();
        if(!userAddressMap.containsKey(user.getUserNo()) || userAddressMap.get(user.getUserNo()).size() == 0) {
            result.put("success",false);
            result.put("msg","用户未维护地址");
            return result;
        }
        if(address.getUserId() != user.getUserNo()) {
            result.put("success",false);
            result.put("msg","用户地址非法");
            return result;
        }
        List<Address> ads = userAddressMap.get(user.getUserNo());
        ads = ads.stream()
                .filter(a -> {
                    if(address.getAddreeId() == a.getAddreeId()
                            &&address.getCity() == a.getCity()
                            && address.getProvince() == a.getProvince()
                            && address.getDetail() == a.getDetail()) {
                        return a.isActive();
                    }
                    return  false;
                })
                .collect(Collectors.toList());
        if(ads == null || ads.size() != 1) {
            result.put("success",false);
            result.put("msg","地址维护校验失败");
            return result;
        }
        result.put("success",true);
        result.put("msg","校验成功");
        return result;
    }

    /**
     * 减库存
     * @param produce
     * @return
     */
    public synchronized static Map<String,Object> decrementReperty(Produce produce) {
        Map<String,Object> result = new HashMap<>();
        int currentNum = atomicInteger.get();
        if(currentNum <= 0) {
            result.put("success",false);
            result.put("msg","当前仓库已无库存！");
            return result;
        }
        int num = produce.getNum();
        if(num <= 0) {
            result.put("success",false);
            result.put("msg","下单产品数量不足1件，无法完成下单！");
            return result;
        }
        if(num > currentNum) {
            result.put("success",false);
            result.put("msg","当前库存已不足！");
            return result;
        }
        for(int i = 0; i < num ; i++){
            atomicInteger.decrementAndGet();
        }
        result.put("success",true);
        result.put("msg","库存扣减已完成！");
        return result;
    }

    /**
     * 校验产品是否有效
     * @param produce  当前产品
     * @return
     */
    public  static Map<String,Object> checkProduce(Produce produce) {
        Map<String,Object> result = new HashMap<>();
        // 查询产品状态
        if(produce == null) {
            result.put("success",false);
            result.put("msg","产品不存在！");
            return result;
        }

        /**
         * 校验产品是否下架
         * 1、下架标识
         * 2、产品得有效时间
         */
        if(produce.isIdRemove() || !CommUtils.DateUtils.checkValidDate(produce.getStartDate(),produce.getEndDate(),true)) {
            result.put("success",false);
            result.put("msg","产品已下架！");
            return result;
        }

        result.put("success",true);
        result.put("msg","产品校验完成！");
        return result;
    }


    /**
     * 校验优惠券
     * @param curUser
     * @param curDiscount
     * @return
     */
    public  static Map<String,Object> checkDiscountCoupon(User curUser, DiscountCoupon curDiscount) {
        Map<String,Object> result = new HashMap<>();

        /**
         * 校验优惠券是否存在
         * 1、传入优惠券为空
         * 2、传入优惠券不在用户优惠券集合中
         */
        if(curDiscount == null) {
            result.put("success",false);
            result.put("msg","优惠券不存在！");
            return result;
        }

        if(!curDiscount.isActive() || !CommUtils.DateUtils.checkValidDate(curDiscount.getStartDate(),curDiscount.getEndDate(),true)) {
            result.put("success",false);
            result.put("msg","优惠券已失效！");
            return result;
        }

        result.put("success",true);
        result.put("msg","优惠券校验完成！");
        return result;
    }




}
